package initialize

import (
	"cgs-server/server"
	"cgs-server/server/base"
	"cgs-server/server/model"
	"go.mongodb.org/mongo-driver/bson"
)

type InitializeRepository interface {
	base.Repository
}

func NewInitializeRepository() InitializeRepository {
	return &initializeRepository{
		base.RepositoryStruct{
			CollectionName: server.ConfigCollectionName,
		},
	}
}

type initializeRepository struct {
	base.RepositoryStruct
}

func (i *initializeRepository) FindOne(mdl *model.DataUserModel) (interface{}, error) {
	if err := i.CheckDB(); err != nil {
		return nil, err
	}
	filter := bson.M{
		"Initialized": true,
	}
	result := &model.SystemConfig{}
	find, err := i.Mongo.FindOne(i.CollectionName, filter, result)
	if find {
		return result, nil
	}
	return nil, err
}

func (i *initializeRepository) Update(mdl *model.DataUserModel) error {
	if config, ok := mdl.Data.(*model.SystemConfig); ok {
		if err := i.CheckDB(); err != nil {
			return err
		}
		filter := bson.M{
			"ID": config.ID,
		}
		update := bson.M{
			"$set": bson.M{
				"Initialized":         config.Initialized,
				"DefaultRegisterRole": config.DefaultRegisterRole,
			},
		}
		_, err := i.Mongo.UpdateOne(i.CollectionName, filter, update)
		return err
	} else {
		return model.NewTypeError("config")
	}
}

func (i *initializeRepository) Insert(mdl *model.DataUserModel) error {
	if config, ok := mdl.Data.(*model.SystemConfig); ok {
		if err := i.CheckDB(); err != nil {
			return err
		}
		config.ResolveEntity(config, mdl.User)
		_, err := i.Mongo.InsertOne(i.CollectionName, config)
		return err
	} else {
		return model.NewTypeError("config")
	}
}
